package com.huluobo.a2112mvvmdouyindemo.live;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huluobo.a2112mvvmdouyindemo.R;
import com.huluobo.a2112mvvmdouyindemo.adapter.GiftAdapter;
import com.huluobo.a2112mvvmdouyindemo.adapter.MessageAdapter;
import com.huluobo.a2112mvvmdouyindemo.databinding.ActivityLiveBinding;
import com.huluobo.a2112mvvmdouyindemo.shop.ShopActivity;
import com.huluobo.a2112mvvmdouyindemo.utils.ImageLoader;
import com.huluobo.mvvm_base.bean.FollowBeanResult;
import com.huluobo.mvvm_base.bean.GiftBeanResult;
import com.huluobo.mvvm_base.bean.Money;
import com.huluobo.mvvm_base.bean.VideoBeanResult;
import com.huluobo.mvvm_base.db.MoneyDao;
import com.huluobo.mvvm_base.net.Const;
import com.huluobo.mvvm_base.view.BaseMVVMActivity;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

public class LiveActivity extends BaseMVVMActivity<ActivityLiveBinding, LiveViewModel> {

    private VideoBeanResult.VideoBean videoBean;

    private GiftAdapter giftAdapter;
    private List<GiftBeanResult.GiftBean> giftBeanList = new ArrayList<>();

    //选中的礼物
    private GiftBeanResult.GiftBean giftBean;

    //用户余额
    private Money money;


    private MessageAdapter messageAdapter;

    private List<MessageEntity> messageEntityList = new ArrayList<>();

    @Override
    protected void initData() {
        viewModel.followSuccess.observe(this, followBeanResult -> {
            if (followBeanResult.getCode() == 200) {
                ToastUtils.showLong(followBeanResult.getMessage());
                dataBinding.liveFollowBtn.setText("已关注");
                dataBinding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red);
                //数据层面也需要修改为已关注,否则下次再点击还是未关注状态,无法调用到取消关注的接口
                videoBean.setGuanzhu(1);
            } else {
                ToastUtils.showLong(followBeanResult.getMessage());
            }
        });

        viewModel.followFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        viewModel.noFollowSuccess.observe(this, followBeanResult -> {
            if (followBeanResult.getCode() == 200) {
                ToastUtils.showLong(followBeanResult.getMessage());
                dataBinding.liveFollowBtn.setText("关注");
                dataBinding.liveFollowBtn.setBackgroundResource(R.drawable.shape_alpha_black);
                videoBean.setGuanzhu(0);
            } else {
                ToastUtils.showLong(followBeanResult.getMessage());
            }
        });

        viewModel.noFollowFailed.observe(this, s -> {
            Log.i("TagA", "取消关注失败:" + s);
        });

        viewModel.getGiftListSuccess.observe(this, giftBeanResult -> {
            if (giftBeanResult.getCode() == 200) {
                giftBeanList.clear();
                giftBeanList.addAll(giftBeanResult.getData());
                giftAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(giftBeanResult.getMessage());
            }

        });

        viewModel.getGiftListFailed.observe(this, s -> {
            Log.i("TagA", "获取礼物列表失败:" + s);
        });

        viewModel.queryMoneySuccess.observe(this, money -> {
            this.money = money;
            dataBinding.liveUserMoneyTv.setText("余额:" + money.money + "抖币");
        });

        viewModel.queryMoneyFailed.observe(this, s -> {
            Log.i("TagA", "查询用户余额失败:" + s);
        });
    }

    @Override
    protected void initView() {
        videoBean = (VideoBeanResult.VideoBean) getIntent().getSerializableExtra("videoBean");
        assert videoBean != null;

        //设置播放器返回按钮
        dataBinding.liveGsyPlayer.getBackButton().setVisibility(View.GONE);
        //设置播放地址
        dataBinding.liveGsyPlayer.setUp(videoBean.getVideopath(), true, "");
        dataBinding.liveGsyPlayer.startPlayLogic();

        //设置直播基本信息
        //头像
        ImageLoader.getInstance().loadCircleImage(this, videoBean.getHeadpath(), dataBinding.liveUserIconIv);
        //作者
        dataBinding.liveUsernameTv.setText(videoBean.getAuthname());
        //关注状态
        dataBinding.liveFollowBtn.setText(videoBean.getGuanzhu() == 0 ? "关注" : "已关注");
        //设置关注按钮的背景
        dataBinding.liveFollowBtn.setBackgroundResource(videoBean.getGuanzhu() == 0 ? R.drawable.shape_alpha_black :
                R.drawable.shape_red);
        //喜欢数量
        dataBinding.liveLikeCountTv.setText(videoBean.getLike_count() + "人喜欢");
        //关注设置点击事件
        dataBinding.liveFollowBtn.setOnClickListener(v -> {
            if (videoBean.getGuanzhu() == 0) {
                //未关注,触发关注接口
                viewModel.followAuth(videoBean.getAuthname());
            } else {
                //已关注,触发取消关注接口
                viewModel.noFollowAuth(videoBean.getAuthname());
            }
        });

        //添加点赞动画图片
        dataBinding.liveLikeView.addLikeImages(
                R.drawable.ic_favorite_0,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_5,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_0
        );

        //点击点赞按钮触发点赞动画
        dataBinding.liveLikeIv.setOnClickListener(v -> {
            dataBinding.liveLikeView.addFavor();
        });

        //单击弹出弹幕输入框布局
        dataBinding.liveDanmuIv.setOnClickListener(v -> {
            dataBinding.liveDanmuLayoutLl.setVisibility(View.VISIBLE);
        });

        //初始化弹幕
        initDanmuView();

        //单击弹幕发送的事件
        dataBinding.liveDanmuSendIv.setOnClickListener(v -> {
            sendDanmu();
        });

        //打开礼物列表
        dataBinding.liveGiftIv.setOnClickListener(v -> {
            openGiftLayout();

        });

        //关闭礼物列表
        dataBinding.liveCloseTv.setOnClickListener(v -> {
            closeGiftLayout();
        });

        //初始化礼物列表
        dataBinding.liveGiftListRv.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter(giftBeanList);
        dataBinding.liveGiftListRv.setAdapter(giftAdapter);

        //礼物列表的点击事件
        giftAdapter.setOnItemClickListener((adapter, view, position) -> {
            giftBean = giftBeanList.get(position);//选中礼物的赋值
            ImageLoader.getInstance().loadCircleImage(this, giftBean.getGiftpath(), dataBinding.liveGiftSelectIv);
            dataBinding.liveGiftNameTv.setText(giftBean.getGiftname());
        });

        //礼物发送的点击事件
        dataBinding.liveGiftSendBtn.setOnClickListener(v -> {
            sendGift();
        });

        //初始化聊天室列表
        messageAdapter = new MessageAdapter(messageEntityList);
        dataBinding.liveChatRoomRv.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.liveChatRoomRv.setAdapter(messageAdapter);

        //初始化环信聊天室
        initChatRoom();

        //聊天框发送点击事件
        dataBinding.liveChatSendIv.setOnClickListener(v -> {
            //聊天假效果
//            MessageEntity messageEntity = new MessageEntity(
//                    SPUtils.getInstance().getString(Const.SP_USERNAME),
//                    dataBinding.liveChatInputEt.getText().toString()
//            );
//            messageEntityList.add(messageEntity);
//            messageAdapter.notifyDataSetChanged();
//            dataBinding.liveChatRoomRv.scrollToPosition(messageEntityList.size() - 1);
//            dataBinding.liveChatInputEt.setText("");
            sendEMChatRoomMessage(Const.CHAT_ROOM_ID, dataBinding.liveChatInputEt.getText().toString());
        });

        dataBinding.liveInputTv.setOnClickListener(v -> dataBinding.liveChatLayoutLl.setVisibility(View.VISIBLE));

        dataBinding.liveCartIv.setOnClickListener(v -> {
            Intent intent = new Intent(this, ShopActivity.class);
            startActivity(intent);
        });
    }

    //发送聊天室消息
    private void sendEMChatRoomMessage(String chatRoomId, String content) {
        //构建一条消息
        EMMessage emMessage = EMMessage.createTextSendMessage(content, chatRoomId);
        emMessage.setChatType(EMMessage.ChatType.ChatRoom);//设置消息类型
        emMessage.setBody(new EMTextMessageBody(content));//构建消息体
        EMClient.getInstance().chatManager().sendMessage(emMessage);//发送消息到服务器
        //设置消息状态监听器
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    MessageEntity messageEntity = new MessageEntity(
                            EMClient.getInstance().getCurrentUser(),
                            content
                    );
                    messageEntityList.add(messageEntity);
                    messageAdapter.notifyDataSetChanged();
                    dataBinding.liveChatRoomRv.scrollToPosition(messageEntityList.size() - 1);
                    dataBinding.liveChatInputEt.setText("");
                });
            }

            @Override
            public void onError(int code, String error) {
                ToastUtils.showLong("消息发送失败:" + error + ",code:" + code);
            }
        });
    }

    //聊天室初始化
    private void initChatRoom() {
        //给聊天室添加监听器,当接收到消息时,需要刷新适配器添加数据源
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        //添加聊天室状态改变的监听器
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(emChatRoomChangeListener);
        //加入聊天室
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.CHAT_ROOM_ID, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(EMChatRoom value) {
                runOnUiThread(() -> {
                    MessageEntity messageEntity = new MessageEntity(
                            "系统",
                            EMClient.getInstance().getCurrentUser() + "加入直播"
                    );
                    messageEntityList.add(messageEntity);
                    messageAdapter.notifyDataSetChanged();
                });
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.i("TagA", "加入聊天室失败");
            }
        });
    }

    //销毁页面时,需要移除监听器,同时退出聊天室
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.CHAT_ROOM_ID);
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        EMClient.getInstance().chatroomManager().removeChatRoomListener(emChatRoomChangeListener);
    }

    //聊天室改变监听器
    private EMChatRoomChangeListener emChatRoomChangeListener = new EMChatRoomChangeListener() {
        @Override
        public void onChatRoomDestroyed(String roomId, String roomName) {

        }

        @Override
        public void onMemberJoined(String roomId, String participant) {
            Log.i("TagA", "有成员进入:" + participant);
        }

        @Override
        public void onMemberExited(String roomId, String roomName, String participant) {
            Log.i("TagA", "有成员退出:" + participant);
        }

        @Override
        public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {

        }

        @Override
        public void onMuteListAdded(String chatRoomId, List<String> mutes, long expireTime) {

        }

        @Override
        public void onMuteListRemoved(String chatRoomId, List<String> mutes) {

        }

        @Override
        public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

        }

        @Override
        public void onAdminAdded(String chatRoomId, String admin) {

        }

        @Override
        public void onAdminRemoved(String chatRoomId, String admin) {

        }

        @Override
        public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

        }

        @Override
        public void onAnnouncementChanged(String chatRoomId, String announcement) {

        }
    };

    //聊天室消息接受监听器
    private EMMessageListener messageListener = messages -> {
        runOnUiThread(() -> {
            for (int i = 0; i < messages.size(); i++) {
                MessageEntity messageEntity = new MessageEntity(
                        messages.get(i).getUserName(),
                        ((EMTextMessageBody) messages.get(i).getBody()).getMessage()
                );

                messageEntityList.add(messageEntity);
                messageAdapter.notifyDataSetChanged();
            }
        });
    };

    //发送礼物的方法
    private void sendGift() {
        //拿到用户余额(查询成功时会给money赋值)
        //扣款逻辑(账号余额是否充足->充足,余额足够->扣款,更新UI,更新数据库中的新余额)
        //检查礼物发送时不能为空,余额也不能为空
        if (giftBean == null || money == null) {
            ToastUtils.showLong("余额不足,或者请选择礼物,再发送");
            return;
        }
        //判断余额小于礼物的价格
        if (money.money < giftBean.getPrice()) {
            ToastUtils.showLong("用户余额不足,请充值");
            return;
        }

        //准备更新余额,新的余额等于当前余额家奴礼物价格
        float newMoney = money.money - giftBean.getPrice();
        //更新UI
        dataBinding.liveUserMoneyTv.setText("余额:" + newMoney + "抖币");

        //给余额赋值
        money.money = newMoney;
        viewModel.updateUserMoney(money);

        //构建一个imageView承载礼物动画
        ImageView giftAnimView = new ImageView(this);
        //直接new的View,没有属性,也没有宽高,都需要设置一个宽高才能显示出来
        //宽高不能直接给View设置,需要通过Layout的Params来设置
        //需要用到哪个Layout上,就创建哪种Layout的Params
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(200, 200);
        giftAnimView.setLayoutParams(params);

        //将构建好的imageView添加到布局上
        dataBinding.liveRootCl.addView(giftAnimView);
        //给imageView添加图片资源
        ImageLoader.getInstance().loadImage(this, giftBean.getGiftpath(), giftAnimView);

        //展示礼物动画
        //获取最大Layout的宽高
        int screenWitch = dataBinding.liveRootCl.getMeasuredWidth();//获取布局的宽
        int screenHeight = dataBinding.liveRootCl.getMeasuredHeight();

        ObjectAnimator translationY = ObjectAnimator.ofFloat(giftAnimView, "translationY", screenHeight,
                screenHeight / 3 * 2, screenHeight / 2);
        ObjectAnimator translationX = ObjectAnimator.ofFloat(giftAnimView, "translationX", screenWitch / 2,
                screenWitch / 3 * 2, screenWitch / 2, screenWitch / 3, screenWitch / 2);

        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftAnimView, "rotation", 0, 1800);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftAnimView, "scaleX", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftAnimView, "scaleY", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(giftAnimView, "alpha", 0.1f, 0.5f, 1.0f, 0.5f, 0.1f);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(3000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(translationY, translationX, rotation, scaleX, scaleY, alpha);

        set.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                //动画开始时,关闭礼物列表
                dataBinding.liveGiftLayoutCl.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //动画结束移除掉礼物的ImageView
                dataBinding.liveRootCl.removeView(giftAnimView);
            }
        });
        set.start();

    }

    private void closeGiftLayout() {
        dataBinding.liveGiftLayoutCl.setVisibility(View.GONE);
    }

    private void openGiftLayout() {
        dataBinding.liveGiftLayoutCl.setVisibility(View.VISIBLE);
        //打开礼物列表加载礼物数据
        viewModel.getGiftList();
        //打开礼物列表查询用户余额
        viewModel.queryMoney(SPUtils.getInstance().getString(Const.SP_USERNAME));
    }

    //发送弹幕
    private void sendDanmu() {
        //获取弹幕内容
        String danmuString = dataBinding.liveDanmuInputEt.getText().toString();
        if (TextUtils.isEmpty(danmuString)) {
            ToastUtils.showLong("请输入弹幕内容,不能为空");
            return;
        }

        //清理弹幕
        dataBinding.liveDanmuView.clear();
        dataBinding.liveDanmuView.removeAllDanmakus(true);

        //创建弹幕的实体
        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);//设置弹幕方向
        danmaku.text = danmuString;//弹幕内容
        danmaku.textSize = 30;//弹幕文字大小
        danmaku.textColor = Color.WHITE;//弹幕颜色
        danmaku.padding = 10;//内边距
        danmaku.setTime(800);

        //添加弹幕到弹幕的View中
        dataBinding.liveDanmuView.addDanmaku(danmaku);
        dataBinding.liveDanmuView.start();

        //清空输入框,和隐藏输入框布局
        dataBinding.liveDanmuInputEt.postDelayed(() -> {
            dataBinding.liveDanmuInputEt.setText("");
            dataBinding.liveDanmuLayoutLl.setVisibility(View.GONE);
        }, 300);

    }

    //初始化需要一个弹幕的上下文
    private DanmakuContext danmakuContext;

    //初始化弹幕
    private void initDanmuView() {
        //1.清理弹幕的缓存
        dataBinding.liveDanmuView.enableDanmakuDrawingCache(false);
        dataBinding.liveDanmuView.clear();
        dataBinding.liveDanmuView.removeAllDanmakus(true);

        //2.创建弹幕的上下文
        danmakuContext = DanmakuContext.create();

        //3.准备弹幕
        dataBinding.liveDanmuView.prepare(new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        }, danmakuContext);
    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }
}